const BAR_BTN_WIDTH = 18

function useDrag(barRef, passedRef, emit, offsetRef) {
  const info = {}

  function onTouchStart(e) {
    info.pageX = e.touches[0].pageX
    info.begin = passedRef.value.offsetWidth - BAR_BTN_WIDTH / 2
  }

  function onTouchMove(e) {
    const moveWidth = barRef.value.offsetWidth - BAR_BTN_WIDTH
    const delta = e.touches[0].pageX - info.pageX
    const newProgress = Math.max(
      Math.min((info.begin + delta) / moveWidth, 1),
      0
    )
    offsetRef.value = newProgress * moveWidth
    emit('progress-changing', newProgress)
  }

  function onTouchEnd(e) {
    const moveWidth = barRef.value.offsetWidth - BAR_BTN_WIDTH
    const newProgress =
      (passedRef.value.offsetWidth - BAR_BTN_WIDTH / 2) / moveWidth
    emit('progress-changed', newProgress)
  }

  function onBarClick(e) {
    const distance =
      e.pageX - barRef.value.getBoundingClientRect().left - BAR_BTN_WIDTH / 2
    const moveWidth = barRef.value.offsetWidth - BAR_BTN_WIDTH
    emit('progress-changed', distance / moveWidth)
  }

  return {
    onTouchStart,
    onTouchMove,
    onTouchEnd,
    onBarClick
  }
}

export default useDrag
